# -*- coding: utf-8 -*-
# @Time : 2020/12/30 下午4:27
# @Author : 蚢
# @Description :使用一等函数实现设计模式：重构“策略”案例实现：实现Order类，支持插入式折扣
# globals()当前模块全局符号表
from abc import ABC, abstractmethod
from collections import namedtuple

# 定义元组类：顾客，积分
Customer = namedtuple('Customer', 'name fidelity')


class LineItem:
    # 商品列表：产品，数量，价格
    def __init__(self, product, quantity, price):
        self.product = product
        self.quantity = quantity
        self.price = price

    def total(self):
        return self.price * self.quantity


class Order:
    # 顾客，购物车，折扣策略
    def __init__(self, customer, cart, promotion=None):
        self.customer = customer
        self.cart = list(cart)
        self.promotion = promotion

    def total(self):  # 总价
        if not hasattr(self, '__total'):
            self.__total = sum(item.total() for item in self.cart)
        return self.__total

    def due(self):  # 折扣价
        if self.promotion is None:
            discount = 0
        else:
            # 1.调用类的方法
            # discount = self.promotion.discount(self)
            # 2.调用方法
            discount = self.promotion(self)

        return self.total() - discount

    # 自定义返回格式
    def __repr__(self):
        fmt = '<Order total:{:.2f} due: {:.2f}>'
        return fmt.format(self.total(), self.due())


# 定义优惠方案
# 抽象基类用abc.ABC声明
class Promotion(ABC):
    @abstractmethod
    def discount(self, order):
        """返回折扣金额"""


class FidelityPromo(Promotion):
    """为积分1000或以上的不怕官，只顾客提供5%的折扣"""
    def discount(self, order):
        return order.total() * .05 if order.customer.fidelity >= 1000 else 0


class BulkItemPromo(Promotion):
    """单品为20个或以上时提供10%折扣"""
    def discount(self, order):
        discount = 0
        for item in order.cart:
            if item.quantity >= 20:
                discount += item.total * .1
        return discount


class LargeOrderPrommo(Promotion):
    """订单中的不同商品达到10个或以上时，提供7%折扣"""
    def discount(self, order):
        distinct_items = {item.product for item in order.cart}
        if len(distinct_items) > 10:
            return order.total() * .07
        return 0


# 1.经典的“策略”模式：抽象基类继承
hang = Customer('Ruan hangj', 1100)
he = Customer('He jiam', 0)
cart = [LineItem('banana', 4, .5), LineItem('apple', 10, 1.5), LineItem('watermellon', 5, 5.0)]
# print(Order(hang, cart, FidelityPromo()))
# print(Order(he, cart, FidelityPromo()))


# 使用函数实现
def fidelity_promo(order):
    """积分折扣策略"""
    return order.total() * .05 if order.customer.fidelity >= 1000 else 0


def bulk_item_promo(order):
    """单个商品折扣策略"""
    discount = 0
    for item in order.cart:
        if item.quantity >= 20:
            discount += item.total() * .1
        return discount


def large_order_promo(order):
    """总数折扣策略"""
    distinct_items = {item.product for item in order.cart}
    if len(distinct_items) >= 10:
        return order.total() * .07
    return 0


# 2.函数实现“策略”模式
print(Order(hang, cart, bulk_item_promo))


# 3.选择最佳策略
def best_promo(order):
    return max(promo(order) for promo in [fidelity_promo, bulk_item_promo, large_order_promo])


# 4.全局策略
all_promo = [globals()[promo] for promo in globals() if promo.endswith('_promo') and promo != 'best_promo']
